{{/* Parse toc.yaml and store the resulting map to $scratch */}}
{{ $scratch := partialCached "utils/tocparser.html" . . }}
{{ $ctx := . }}

{{/* Get the name of the first section */}}
{{ $firstSection := (index ($scratch.GetSortedMapValues "sections") 0).title }}

{{/* Render the top-nav in sidebar for small screens */}}
<nav class="text-sm pb-4 gap-4 flex md:hidden flex-col justify-evenly">
  <div class="text-gray-light dark:text-gray-dark">Main sections</div>
  {{ range site.Menus.main }}
  <div class="pl-2 underline-offset-8 decoration-2 hover:underline decoration-blue-light dark:decoration-blue-dark hover:opacity-75
      {{- if eq $firstSection .Name }}
        underline
      {{- end }}">
    <a href="{{ .URL }}">{{ .Name }}</a>
  </div>
  {{ end }}
</nav>
{{ if $firstSection }}
{{ $allSections := slice }}
{{ range $i, $e := ($scratch.GetSortedMapValues "sections") }}
{{ $allSections = $allSections | append (index $e "title") }}
{{ end }}
<nav id="sectiontree" class="text-sm flex flex-col">
  <div class="block py-4 md:hidden text-gray-light dark:text-gray-dark">This section</div>
  {{/* The current page is in the table of contents */}}
  <ul>
    {{/* Walk the toc.yaml nodes under the current main section */}}
    {{ range (index site.Data.toc $firstSection) }}
    {{ template "tocRender" (dict "ctx" $ctx "entry" . "sections" $allSections) }}
    {{ end }}
  </ul>
</nav>
{{ end }}

{{/* Recursive template for sidebar items */}}
{{ define "tocRender" }}
{{ $ctx := .ctx }}
{{ $sections := .sections }}
{{ if .entry.sectiontitle }}
{{ $expanded := in $sections .entry.sectiontitle }}
{{/* .entry is a section */}}
<li>
  {{/* See event handler in assets/js/src/sidebar.js */}}
  <button class="rounded px-4 sidebar-hover w-full flex items-center justify-between">
    <span class="py-2 truncate flex items-center gap-2">
      {{ markdownify .entry.sectiontitle }}
    </span>
    <span class="icon-svg {{ if $expanded }}hidden{{ end }}">
      {{ partialCached "icon" "expand_more" "expand_more" }}
    </span>
    <span class="icon-svg {{ if not $expanded }}hidden{{ end }}">
      {{ partialCached "icon" "expand_less" "expand_less" }}
    </span>
  </button>
  <ul class="{{if not $expanded}}hidden {{end}}ml-3">
    {{ range .entry.section }}
    {{ template "tocRender" (dict "entry" . "ctx" $ctx "sections" $sections ) }}
    {{ end }}
  </ul>
</li>
{{ else }}
{{/* .entry is a page */}}
{{ $isCurrent := eq (urls.Parse $ctx.Permalink).Path .entry.path }}
<li class="pl-4 sidebar-hover rounded
  {{ if $isCurrent }} bg-gray-light-200 dark:bg-gray-dark-200{{ end }}">
  <a {{ if $isCurrent }}aria-current="page" {{ end }} class="py-2 w-full truncate block"
      href="{{ .entry.path }}" title="{{ markdownify .entry.title }}"
      ><span class="flex items-center gap-2">{{ markdownify .entry.title }}</span>
  </a>
</li>
{{ end }}
{{ end }}
